<script lang="ts" setup generic="T extends BaseEntity">
import { activeById, logicalDeleteById, physicalDeleteByIdInFlowable } from '@/index';
import type { BaseEntity } from '@/index.d';
import { type ElTable } from 'element-plus';

const props = defineProps({
  height: Number,
  tableData: Array,
  rowSelected: Array<T>,
  selection: { type: Boolean, default: false },
  title: { type: String, required: true },
  baseUrl: { type: String, required: true },
  loading: { type: Boolean, default: false },
  logicDelete: { type: Boolean, default: false },
  id: { type: Boolean, default: false },
  version: { type: Boolean, default: false },
  operateRecord: { type: Boolean, default: false },
  operateColumn: { type: Boolean, default: false }
});

const tableRef = ref<InstanceType<typeof ElTable>>();

const emit = defineEmits<{
  (e: 'handleView', row: any): void;
  (e: 'handleUpdate', row: T): void;
  (e: 'handleRowClick', row: T): void;
  (e: 'handleReload'): void;
}>();

const handleDelete = async (id: string) => {
  const res = await physicalDeleteByIdInFlowable(props.baseUrl, id);
  res && emit('handleReload');
};

const handleLogicDelete = async (row: T) => {
  if (row.deleted) {
    const res = await logicalDeleteById(props.baseUrl, row.id as number);
    res && emit('handleReload');
  } else {
    const res = await activeById(props.baseUrl, row.id as number);
    res && emit('handleReload');
  }
};

watch(
  () => props.rowSelected,
  value => {
    value?.forEach(item => tableRef.value?.toggleRowSelection(item, true));
  }
);
</script>
<template>
  <el-table
    ref="tableRef"
    :data="props.tableData"
    :height
    v-loading="loading"
    highlight-current-row
    v-bind="$attrs"
    stripe
    border
    fit
  >
    <slot name="columns"></slot>
    <hq-table-column
      label="操作"
      fixed="right"
      width="120px"
      align="center"
      v-if="props.operateColumn"
    >
      <template #default="{ row }">
        <el-button
          link
          type="primary"
          size="small"
          @click="$emit('handleView', row)"
          v-button="`查看${props.title}`"
        >
          查看
        </el-button>
      </template>
    </hq-table-column>
  </el-table>
</template>
<style lang="scss" scoped></style>
